//
//  NetworkTool.swift
//  weibo
//
//  Created by 黄龙飞 on 15/11/24.
//  Copyright © 2015年 黄龙飞. All rights reserved.
//

import UIKit
import AFNetworking
/// HTTP 请求方法枚举
enum NBRequestMethod: String {
    case GET = "GET"
    case POST = "POST"
}

// MARK: 网络工具AFHTTPSessionManager
class NetworkTools: AFHTTPSessionManager {
    private let appKey = "293254753"
    private let appSecret = "963d4adf6546d7669cd5672c75af5866"
    private let redirectUrl = "http://www.baidu.com"
    
    typealias NBRequestCallBack = (result: AnyObject?, error: NSError?)->()
    
    // 单例
    static let sharedTools: NetworkTools = {
        
        let tools = NetworkTools(baseURL: nil)
        
        // 设置反序列化数据格式 - 系统会自动将 OC 框架中的 NSSet 转换成 Set
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tools
    }()
}

// MARK: - 用户信息相关方法
extension NetworkTools{
///parameter uid:
///parameter accessToken：accessToken
/// - parameter finished:完成回调
    func loadUserInfo(uid: String, finished: NBRequestCallBack){
        guard var params = UserAccountViewModel.sharedUserAccount.tokenDict else{
        finished(result: nil, error: NSError(domain: "***.buterfly.error", code: 110, userInfo: ["message": "token字典为空"]))
            return
        }
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        params["uid"]=uid
        
        request(.GET, URLString: urlString, parameters: params, finished: finished)
    }
}

// MARK: - OAuth 相关方法
extension NetworkTools {
    
    /// OAuth 授权 URL
    /// - see: [http://open.weibo.com/wiki/Oauth2/authorize](http://open.weibo.com/wiki/Oauth2/authorize)
    var oauthURL: NSURL {
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirectUrl)"
        print(urlString)
        return NSURL(string: urlString)!
    }
    
    /// 加载 AccessToken
    //
    func loadAccessToken(code: String, finished: NBRequestCallBack) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let params = ["client_id": appKey,
            "client_secret": appSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirectUrl]
        
        request(.POST, URLString: urlString, parameters: params, finished: finished)
//         1> 创建序列
//        responseSerializer = AFHTTPResponseSerializer()
        
//         2> 发起网络请求
//        request(<#T##method: NBRequestMethod##NBRequestMethod#>, URLString: <#T##String#>, parameters: <#T##[String : AnyObject]?#>, finished: <#T##NBRequestCallBack##NBRequestCallBack##(result: AnyObject?, error: NSError?) -> ()#>)
        
//        POST(<#T##URLString: String##String#>, parameters: <#T##AnyObject?#>, success: <#T##((NSURLSessionDataTask, AnyObject) -> Void)?##((NSURLSessionDataTask, AnyObject) -> Void)?##(NSURLSessionDataTask, AnyObject) -> Void#>, failure: <#T##((NSURLSessionDataTask?, NSError) -> Void)?##((NSURLSessionDataTask?, NSError) -> Void)?##(NSURLSessionDataTask?, NSError) -> Void#>)
//        POST(urlString, parameters: params, success: { (_, result) -> Void in
//            
//            // 将二进制数据转换成字符串
//            let json = NSString(data: result as! NSData, encoding: NSUTF8StringEncoding)
//            
//            print(json)
//            
//            }, failure: nil)
    }
}

// MARK: - 封装 AFN 网络方法
extension NetworkTools {
    
    /// 网络请求
    ///
    /// - parameter method:     GET / POST
    /// - parameter URLString:  URLString
    /// - parameter parameters: 参数字典
    /// - parameter finished:   完成回调
    private func request(method: NBRequestMethod, URLString: String, parameters: [String: AnyObject]?, finished: NBRequestCallBack) {
        
        // 定义成功回调
        let success = { (task: NSURLSessionDataTask, result: AnyObject) -> Void in
            finished(result: result, error: nil)
        }
        
        // 定义失败回调
        let failure = { (task: NSURLSessionDataTask?, error: NSError) -> Void in
            print(error)
            finished(result: nil, error: error)
        }
        
        if method == NBRequestMethod.GET {
            GET(URLString, parameters: parameters, success: success, failure:failure)
        } else {
            POST(URLString, parameters: parameters, success: success, failure:failure)
        }
    }
}
